package Service.StatisticalReport.StatisticalReportImpl;

import Model.StatisticalReport.HomeDetail;
import Model.StatisticalReport.Report;
import Model.StatisticalReport.ReportDetail;
import Service.StatisticalReport.ReportResolver;
import Service.StatisticalReport.ReportResolverError;
import utils.JsonUtil;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ReportLineResolver implements ReportResolver {
    //private final String pattern = ;
    private final Pattern pattern = Pattern.compile("^[!-/\\s]");//匹配符号字符开头

    private BufferedReader buffer;

    private StringBuilder sb;

    private ReportResolverError resolverError;
    private boolean fNext = false;

    private List<String> header;

    private Class entity;

    public ReportLineResolver(Class<? extends Report> entity){
        this.entity = entity;
    }

    static List<String> split(String line){
        List<String> list = new ArrayList<>(24);
        StringTokenizer elems = new StringTokenizer(line);
        while (elems.hasMoreTokens()){
            list.add(elems.nextToken());
        }

        //System.out.println(list);
        return list;
    }

    public boolean begin(InputStream inputStream, String charset) {
        Reader reader;
        try{
            reader = new InputStreamReader(inputStream, charset);
        }catch (UnsupportedEncodingException e){
            return false;
        }

        buffer = new BufferedReader(reader);
        //解析表头
        String line;  //按行读取
        while (true){
            try{
                line = buffer.readLine();  //按行读取
            }catch (IOException e){
                e.printStackTrace();
                return false;
            }
            if(line == null){
                return false;
            }
            //编译正则
            Matcher matcher = pattern.matcher(line);
            if(!matcher.lookingAt()){
                break;
            }
        }

        header = split(line);

        //TODO: 检查表头是否为需要的表头

        //数据格式化建造器
        sb = new StringBuilder(512);

        fNext = true;
        return true;
    }

    public ReportResolverError getResolverError() {
        return resolverError;
    }

    public void setResolverError(ReportResolverError resolverError) {
        this.resolverError = resolverError;
    }

    @Override
    public boolean hasNext() {
        return fNext;
    }

    public Report parse(List<String> value, List<String> header){
        sb.setLength(0);
        sb.append('{');
        for(int i=0; i < header.size(); i++){
            sb.append('"');
            sb.append(header.get(i));
            sb.append("\":\"");
            sb.append(value.get(i));
            sb.append("\",");
        }
        sb.deleteCharAt(sb.length() - 1);
        sb.append('}');
        //System.out.println(sb.capacity());
        Report detail = null;
        try{
            detail = (Report) JsonUtil.Json2Pojo(sb.toString(), entity);
        }catch (IOException e){
            ReportResolverError resolverError = new ReportResolverError();
            resolverError.setContent(value.toString());
            resolverError.setMsg(e.getMessage());
            this.setResolverError(resolverError);
        }
        return detail;
    }

    /**
     * 下一个
     * @return
     */
   public Report next(){
       //清除错误
       resolverError = null;
       if (header == null){return null;}
       String line;

       while(true){
           try{
               line = buffer.readLine();  //按行读取
           }catch (IOException e){
               e.printStackTrace();
               resolverError = new ReportResolverError();
               resolverError.setContent("");
               resolverError.setMsg(e.getMessage());
               fNext = false;
               return null;
           }
           if(line == null){
               fNext = false;
               return null;
           }
           //空字符
           if(line.isEmpty()){
                continue;
           }
           //编译正则
           Matcher matcher = pattern.matcher(line);
           if(!matcher.lookingAt()){
               break;
           }
       }
       List<String> list = split(line);
       if (list.size() != header.size()){
           resolverError = new ReportResolverError();
           resolverError.setContent(line);
           resolverError.setMsg("不完整的数据行");
           return null;
       }
       return parse(list, header);
   }

}
